package design;

import java.util.Stack;

/**
 * @author pengfei.hpf
 * @date 2020/3/19
 * @verdion 1.0.0
 */
public class SortedStack {

    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public SortedStack() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int val) {
        if(stack1.size() > stack2.size()){
            move(stack1, stack2, val);
        } else {
            move(stack2, stack1, val);
        }
    }

    private void move(Stack<Integer> s1, Stack<Integer> s2, int val){
        if(s1.isEmpty() || val <= s1.peek()){
            s1.push(val);
            return;
        }
        if(s2.isEmpty() ||val <= s2.peek()){
            s2.push(val);
            return;
        }
        int min = s1.peek();
        while(!s2.isEmpty() && s2.peek() < val){
            s1.push(s2.pop());
        }
        s2.push(val);
        while(s1.peek() != min){
            s2.push(s1.pop());
        }
    }

    public void pop() {
        if(isEmpty()){
            return;
        }
        if(stack1.isEmpty()){
            stack2.pop();
            return;
        }
        if(stack2.isEmpty()){
            stack1.pop();
            return;
        }
        if(stack1.peek() < stack2.peek()){
            stack1.pop();
            return;
        }
        stack2.pop();
    }

    public int peek() {
        if(isEmpty()){
            return -1;
        }
        if(stack1.isEmpty()){
            return stack2.peek();
        }
        if(stack2.isEmpty()){
            return stack1.peek();
        }
        if(stack1.peek() < stack2.peek()){
            return stack1.peek();
        }
        return stack2.peek();
    }

    public boolean isEmpty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    public static void main(String[] args){
        SortedStack ss = new SortedStack();

        ss.push(5);
        ss.push(1);
        ss.push(2);
        ss.push(4);
        ss.push(7);
        ss.push(6);
        ss.push(3);

        System.out.println(ss.peek());
        ss.pop();
        System.out.println(ss.peek());
        ss.pop();
        System.out.println(ss.peek());
        ss.pop();
        System.out.println(ss.peek());
        ss.pop();
        System.out.println(ss.peek());
        ss.pop();
        System.out.println(ss.peek());
        ss.pop();
        System.out.println(ss.peek());

    }
}
